/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.employee.web;

import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.CacheUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreCardTemplateAll;
import com.chlitina.store.modules.base.entity.StoreCardTemplateDuration;
import com.chlitina.store.modules.base.entity.StoreCardTemplateProduct;
import com.chlitina.store.modules.base.entity.StoreCardTemplateTimes;
import com.chlitina.store.modules.base.service.StoreCardTemplateAllService;
import com.chlitina.store.modules.base.service.StoreCardTemplateDurationService;
import com.chlitina.store.modules.base.service.StoreCardTemplateProductService;
import com.chlitina.store.modules.base.service.StoreCardTemplateTimesService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingCard;
import com.chlitina.store.modules.employee.entity.StoreBonusSettingTemplateCard;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.employee.service.StoreBonusSettingCardService;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 新开卡或卡充值提成设定Controller
 * @author liujiang
 * @version 2013-11-13
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/employee/storeBonusSettingCard")
public class StoreBonusSettingCardController extends BaseController {

	@Autowired
	private StoreBonusSettingCardService storeBonusSettingCardService;
	@Autowired
	private StoreCardTemplateAllService storeCardTemplateAllService;
	@Autowired
	private StoreCardTemplateDurationService storeCardTemplateDurationService;
	@Autowired
	private StoreCardTemplateProductService storeCardTemplateProductService;
	@Autowired
	private StoreCardTemplateTimesService storeCardTemplateTimesService;
	@Autowired
	private EmployeeService employeeService;
	
	@ModelAttribute
	public StoreBonusSettingCard get(@RequestParam(required=false) Long id) {
		if (id != null){
			return storeBonusSettingCardService.get(id);
		}else{
			return new StoreBonusSettingCard();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required=false)String currentSelectId, Long employeeId, StoreBonusSettingCard storeBonusSettingCard, HttpServletRequest request, HttpServletResponse response, Model model) {
		Employee employee = employeeService.get(employeeId);
		CacheUtils.put("current_bonus_employee", employee);
		Page<StoreBonusSettingCard> page = storeBonusSettingCardService.find(new Page<StoreBonusSettingCard>(request, response), employeeId); 
        model.addAttribute("page", page);
        model.addAttribute("cardNameMap", getCardNameMap(page.getList()));
        model.addAttribute("employee", employee);
        model.addAttribute("currentSelectId", currentSelectId);
		return "modules/employee/storeBonusSettingCardList";
	}

	private Map<String, String> getCardNameMap(List<StoreBonusSettingCard> list){
		 Map<String, String> cardNameMap = Maps.newHashMap();
        for (StoreBonusSettingCard card : list) {
			int type = card.getCard_template_type();
			Long id = card.getCard_template_id();
			String name = "";
			if(type == StoreBonusSettingCard.CARD_TYPE_ALL) {
				name = storeCardTemplateAllService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_DURATION) {
				name = storeCardTemplateDurationService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_PRODUCT) {
				name = storeCardTemplateProductService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_TIMES) {
				name = storeCardTemplateTimesService.get(id).getName();
			}
			cardNameMap.put(type +"-"+ id, name);
		}
        return cardNameMap;
	}
	
	@RequestMapping(value = "form")
	public String form(StoreBonusSettingCard storeBonusSettingCard, Model model) {
		model.addAttribute("storeBonusSettingCard", storeBonusSettingCard);
		int type = storeBonusSettingCard.getCard_template_type();
		Long id = storeBonusSettingCard.getCard_template_id();
		String name = "";
		if(id != null) {
			if(type == StoreBonusSettingCard.CARD_TYPE_ALL) {
				name = storeCardTemplateAllService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_DURATION) {
				name = storeCardTemplateDurationService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_PRODUCT) {
				name = storeCardTemplateProductService.get(id).getName();
			} else if(type == StoreBonusSettingCard.CARD_TYPE_TIMES) {
				name = storeCardTemplateTimesService.get(id).getName();
			}
		}
		model.addAttribute("cardName", name);
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		model.addAttribute("employee", employee);
		return "modules/employee/storeBonusSettingCardForm";
	}

	@RequestMapping(value = "add")
	public String add(StoreBonusSettingCard storeBonusSettingCard, Model model) {
		model.addAttribute("storeBonusSettingCard", storeBonusSettingCard);
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		model.addAttribute("employee", employee);
		return "modules/employee/storeBonusSettingCardAdd";
	}
	
	@RequestMapping(value = "save")
	public String save(String pageNo, StoreBonusSettingCard storeBonusSettingCard, Model model, RedirectAttributes redirectAttributes) {
		Store store = StoreUtils.getStore();
		storeBonusSettingCard.setStore(store);
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		storeBonusSettingCard.setEmployee(employee);
		storeBonusSettingCard.setBonus_rate(storeBonusSettingCard.getBonus_rate()/100);
		if (!beanValidator(model, storeBonusSettingCard)){
			return form(storeBonusSettingCard, model);
		}
		storeBonusSettingCardService.save(storeBonusSettingCard);
		addMessage(redirectAttributes, "保存新开卡或卡充值提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingCard/?employeeId=" + employee.getId()+"&pageNo=" + pageNo +"&currentSelectId=" + storeBonusSettingCard.getId();
	}
	
	@RequestMapping(value = "addNew")
	public String addNew(String cardIds, StoreBonusSettingCard storeBonusSettingCard, Model model, RedirectAttributes redirectAttributes) {
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		storeBonusSettingCard.setBonus_rate(storeBonusSettingCard.getBonus_rate()/100);
		float bonus_rate = storeBonusSettingCard.getBonus_rate();
		int type = storeBonusSettingCard.getCard_template_type();
		int btype = storeBonusSettingCard.getBonus_type();
		float fixed_money = storeBonusSettingCard.getFixed_money();
		List<Long> saveIds = Lists.newArrayList();
		String [] cardList = cardIds.split(",");
		for (int i = 0; i < cardList.length; i++) {
			String id = cardList[i];
			if (StringUtils.isNotEmpty(id)){
				long productId = Long.parseLong(id);
				saveIds.add(productId);
			}
		}
		for (Long id : saveIds) {
			StoreBonusSettingCard item = new StoreBonusSettingCard();
			item.setStore(StoreUtils.getStore());
			item.setEmployee(employee);
			item.setCard_template_type(type);
			item.setBonus_type(btype);
			item.setFixed_money(fixed_money);
			item.setBonus_rate(bonus_rate);
			item.setCard_template_id(id);
			storeBonusSettingCardService.save(item);
		}
		addMessage(redirectAttributes, "保存新开卡或卡充值提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingCard/?employeeId=" + employee.getId();
	}
	
	@RequestMapping(value = "copy")
	public String copy(@RequestParam(required=false) int ifModify, Model model, RedirectAttributes redirectAttributes) {
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		storeBonusSettingCardService.copy(employee, ifModify);
		addMessage(redirectAttributes, "复制模板成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingCard/?employeeId=" + employee.getId();
	}
	
	@RequestMapping(value = "delete")
	public String delete(StoreBonusSettingCard storeBonusSettingCard, RedirectAttributes redirectAttributes) {
		long employeeId = storeBonusSettingCard.getEmployee().getId();
		storeBonusSettingCardService.delete(storeBonusSettingCard);
		addMessage(redirectAttributes, "删除新开卡或卡充值提成设定成功");
		return "redirect:"+Global.ADMIN_PATH+"/employee/storeBonusSettingCard/?employeeId=" + employeeId;
	}

	@ResponseBody
	@RequestMapping(value = "cardTemplateData")
	public String cardTemplateData(@RequestParam(required=false) int type, HttpServletResponse response) {
		response.setContentType("application/json; charset=UTF-8");
		Employee employee = (Employee) CacheUtils.get("current_bonus_employee");
		Long employeeID = employee.getId();
		Set<Map<String, Object>> set = Sets.newHashSet();
		List<Long> existId = storeBonusSettingCardService.getExistTemplateId(employeeID, type);
		if(type == StoreBonusSettingCard.CARD_TYPE_ALL) {
			List<StoreCardTemplateAll> list = storeCardTemplateAllService.getByStore();
			for (StoreCardTemplateAll template : list) {
				Long id = template.getId();
				if(existId.contains(id)) {
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", id);
				map.put("name", template.getName());
				set.add(map);
			}
		} else if(type == StoreBonusSettingCard.CARD_TYPE_DURATION) {
			List<StoreCardTemplateDuration> list = storeCardTemplateDurationService.getByStore();
			for (StoreCardTemplateDuration template : list) {
				Long id = template.getId();
				if(existId.contains(id)) {
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", id);
				map.put("name", template.getName());
				set.add(map);
			}
		} else if(type == StoreBonusSettingCard.CARD_TYPE_PRODUCT) {
			List<StoreCardTemplateProduct> list = storeCardTemplateProductService.getByStore();
			for (StoreCardTemplateProduct template : list) {
				Long id = template.getId();
				if(existId.contains(id)) {
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", id);
				map.put("name", template.getName());
				set.add(map);
			}
		} else if(type == StoreBonusSettingCard.CARD_TYPE_TIMES) {
			List<StoreCardTemplateTimes> list = storeCardTemplateTimesService.getByStore();
			for (StoreCardTemplateTimes template : list) {
				Long id = template.getId();
				if(existId.contains(id)) {
					continue;
				}
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", id);
				map.put("name", template.getName());
				set.add(map);
			}
		}
		return JsonMapper.getInstance().toJson(set);
	}
}
